package com.zhangli.mytoolkit;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.zhangli.Model.TaskDataBaseHelper;

import java.io.File;

/**
 * 自定义的Android代码和JavaScript代码之间的桥梁类
 * @author 1
 * 
 */
public class JavascriptInterfaceImpl {

	private final String TAG = JavascriptInterfaceImpl.class.getSimpleName();
	private Context mContext;
	private WebView mWebView;
	private Handler mHandler;
	TaskDataBaseHelper task_helper;
	/** Instantiate the interface and set the context */
	JavascriptInterfaceImpl(Context c, WebView webView) {
		mContext = c;
		mWebView = webView;
		mHandler = new Handler(Looper.getMainLooper());

		task_helper = new TaskDataBaseHelper(c);
	}

	private void toast(final String text)
	{
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
			}
		});
	}

    private String html_encode(String str)
    {
        String s = "";
        if (str.length() == 0) return "";
        s = str.replace("&", "&gt;");
        s = s.replace("<", "&lt;");
        s = s.replace(">", "&gt;");
        s = s.replace(" ", "&nbsp;");
        s = s.replace("'", "&#39;");
        s = s.replace("\"", "&quot;");
        s = s.replace("\n", "<br>");
        return s;
    }

	@JavascriptInterface
	public void update_task_list(final String status) {
		//new Thread() {
		//	@Override
		//	public void run() {
				//SystemClock.sleep(5 * 1000);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Cursor c =  task_helper.getAll(status,"priority DESC, date DESC");
						//mWebView.loadUrl("javascript:clean_task_list()");
						while(c.moveToNext()) {
                            String title = html_encode(task_helper.getName(c));
                            String content = html_encode(task_helper.getContent(c));
							String parameters="javascript:add_item(\""+task_helper.getId(c)+"\",\""+title+"\",\""+content+"\",\""+task_helper.getDate(c)+"\",\""+task_helper.getStatus(c)+"\");";
							mWebView.loadUrl(parameters);
						}
						c.close();
					}
				});
		//	}
		//}.start();
	}

	@JavascriptInterface
	public void add_new_task(String title, String content, String priority) {
		task_helper.insert(title,content, priority);
	}
	@JavascriptInterface
	public void update_task(String id, String title, String content, String priority) {
		task_helper.update(id,title,content,priority);
	}

	@JavascriptInterface
	public void update_task_status(String id,String new_status) {
		task_helper.update_status(id,Integer.parseInt(new_status));
	}

    @JavascriptInterface
    public void mend_task(final String id)
    {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("file:///android_asset/task_edit.html?id=" + id);
            }
        });
    }

	static 		String id;
    static 		String title;
	static 		String content;
	static      String priority;

	@JavascriptInterface
	public void get_task_by_id(String id)
	{
		this.id = id;
		Cursor c = task_helper.getById(id);
		if(c.moveToNext()) {
			title = task_helper.getName(c);
			content = task_helper.getContent(c);
			priority = task_helper.getPriority(c);
		}
	}

	@JavascriptInterface
	public String get_title_by_id(String id)
	{
		if(!this.id.equals(id))
			return "";
		return title;
	}
	@JavascriptInterface
	public String get_content_by_id(String id)
	{
		if(!this.id.equals(id))
			return "";
		return content;
	}
	@JavascriptInterface
	public String get_priority_by_id(String id)
	{
		if(!this.id.equals(id))
			return "";
		return priority;
	}


    @JavascriptInterface
	public void import_from_xml()
	{
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyToolKit/backup.xml";
		boolean success = task_helper.import_by_D(path);
		toast("import xml done " + (success?"successed":"failed"));
	}

	@JavascriptInterface
	public void export_to_csv()
	{
		String outputFile = Environment.getExternalStorageDirectory().
				getAbsolutePath() + "/MyToolKit";

		File file = new File(outputFile);
		if (!file.exists()) {
			file.mkdirs();
		}
		String path = outputFile + "/backup.csv";
		boolean success = task_helper.export_as_csv(path);
		toast("export csv done " + (success?"successed":"failed"));
	}

	@JavascriptInterface
	public void import_from_csv()
	{
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyToolKit/backup.csv";
		boolean success = task_helper.import_as_csv(path);
		toast("import csv done " + (success?"successed":"failed"));
	}


}
